
//
//  CaiGouGuiXiaDetialViewController.m
//  tangshantongjiAPP
//
//  Created by yuntai on 2018/4/24.
//  Copyright © 2018年 yuntai. All rights reserved.
//

#import "CaiGouGuiXiaDetialViewController.h"
#import "FullMainCollectionViewCell.h"
#import "UICollectionView+HD_NoList.h"
#import "CommonModel.h"


@interface CaiGouGuiXiaDetialViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic,strong)UICollectionView *collectionview;
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) CommonModel *model;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, assign) BOOL isChange;
@end

static NSString *fullMainCollectionCellID = @"FullMainCollectionViewCell";

@implementation CaiGouGuiXiaDetialViewController

-(NSMutableArray *)array{
    if (_array == nil) {
        _array = [NSMutableArray array];
    }
    return _array;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((kScreenBoundWidth-90)/2,(kScreenBoundWidth-90)/2+10); ;
    layout.minimumInteritemSpacing = 30;
    layout.minimumLineSpacing = 30;
    [layout setSectionInset:UIEdgeInsetsMake(30, 30, 50, 30)];
    
    self.collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, kNavigationHeight, kScreenBoundWidth, kScreenBoundHeight-kNavigationHeight-49) collectionViewLayout:layout];
    self.collectionview.delegate = self;
    self.collectionview.dataSource = self;
    self.collectionview.backgroundColor = kBGColor;
    [self.view addSubview:self.collectionview];
    
    [self.collectionview registerNib:[UINib nibWithNibName:fullMainCollectionCellID bundle:nil] forCellWithReuseIdentifier:fullMainCollectionCellID];
    
    UIButton *bottombtnn = [[UIButton alloc]init];
    [bottombtnn setTitle:@"保  存" forState:UIControlStateNormal];
    [bottombtnn setBackgroundColor:kNavigationColor];
    [bottombtnn addTarget:self action:@selector(saveBtnClickAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: bottombtnn];
    
    [bottombtnn mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
            
        } else {
            // Fallback on earlier versions
            make.right.left.bottom.equalTo(self.view);
        }
        if (self.isCanEdit) {
            make.height.mas_equalTo(49);

        }else{
            make.height.mas_equalTo(0);

        }
            
    }];
    
    [self getdata];
}

- (void)saveBtnClickAction{
    if (self.isChange == NO) {
        [HUDManager showWarningWithText:@"没有修改无需保存"];
        return;
    }
    
    [self saveAction];
}


#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 2+self.model.images.count;
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    FullMainCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:fullMainCollectionCellID forIndexPath:indexPath];
    
    switch (indexPath.row) {
        case 0:
            cell.nameLabel.text = @"报表照片";
            [cell.imageIconView sd_setImageWithURL:[NSURL URLWithString:self.model.img1] placeholderImage:[UIImage imageNamed:@"ic_default_img"]  completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                
            }];
            break;
            
        case 1:
            cell.nameLabel.text = @"台账照片";
            [cell.imageIconView sd_setImageWithURL:[NSURL URLWithString:self.model.img2] placeholderImage:[UIImage imageNamed:@"ic_default_img"]  completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                
            }];
            break;
            
        default:
            cell.nameLabel.text = [NSString stringWithFormat:@"第%ld张凭证照片",indexPath.row-1];
            [cell.imageIconView sd_setImageWithURL:[NSURL URLWithString:self.model.images[indexPath.row-2]] placeholderImage:[UIImage imageNamed:@"ic_default_img"]  completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                
            }];
            break;
    }
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    if (self.isCanEdit) {
        self.indexPath = indexPath;
        weakself(self)
        [[CameraTakeMamanger sharedInstance] cameraSheetInController:self handler:^(UIImage *image, NSString *imagePath) {
            weakself.isChange = YES;
            [HUDManager showLoadingHUDView:weakself.view];
            [NetWork PostUpLoadImageWithImages:image index:indexPath.row pid:@"" successBlock:^(NSString *imagePath) {
                [HUDManager hideHUDView];
                if (indexPath.row ==0 ) {
                    weakself.model.img1 =  imagePath;

                }else if(indexPath.row ==1){
                    weakself.model.img2 =  imagePath;
                }else{
                    weakself.model.images[indexPath.row-2] = imagePath;
                }
                [weakself.collectionview reloadItemsAtIndexPaths:@[indexPath]];
                
            } FailureBlock:^(NSString *msg) {
                [HUDManager hideHUDView];
                [HUDManager showWarningWithText:@"上传失败请重试"];
                
            } errorBlock:^(id error) {
                [HUDManager hideHUDView];
                [HUDManager showWarningWithText:@"上传失败请重试"];
            }];
            
        } cancelHandler:^{
            
        }];
        
    }else{
        
    }
    
}



- (void)getdata{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    
    NSString *subUrl = nil;
    if(self.type == FullGuiXiaGongYe){
        subUrl = @"api/gxcp/getOne.ajax";
        [params setValue:kTokenID forKey:@"token"];
        [params setValue:self.modelId forKey:@"id"];
        
    }else{
        subUrl = @"api/cgjl/getOne.ajax";
        [params setValue:kTokenID forKey:@"token"];
        [params setValue:self.modelId forKey:@"id"];
        
    }
    [HUDManager showLoadingHUDView:self.view];
    [NetWork PostNetWorkWithUrl:subUrl with:params successBlock:^(NSDictionary *dic) {
        [HUDManager hideHUDView];
        NSDictionary *tempDic = nil;
        tempDic = dic[@"data"];
        self.model = [CommonModel mj_objectWithKeyValues:tempDic];
        
        [self.collectionview reloadData];
       
        
    } FailureBlock:^(NSString *msg) {
        [HUDManager showWarningWithText:msg];
        BOOL ishow = self.array.count ? NO : YES;
        [self.collectionview showNoView:nil image:nil certer:CGPointZero isShow:ishow];
        
        
    } errorBlock:^(id error) {
        BOOL ishow = self.array.count ? NO : YES;
        [self.collectionview showNoView:nil image:nil certer:CGPointZero isShow:ishow];
        
        
    }];
    
}

- (void)saveAction{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    
    NSString *subUrl = nil;
    if(self.type == FullGuiXiaGongYe){
        subUrl = @"api/gxcp/update.ajax";
        [params setValue:kTokenID forKey:@"token"];
        [params setValue:self.modelId forKey:@"id"];
        [params setValue:self.model.img1?:@"" forKey:@"img1"];
        [params setValue:self.model.img2?:@"" forKey:@"img2"];
        __block NSString *tempImg3Str = nil;
        [self.model.images enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (tempImg3Str== nil) {
                tempImg3Str = obj;
            }else{
                tempImg3Str = [NSString stringWithFormat:@"%@,%@",tempImg3Str,obj];
            }
        }];
        [params setValue:tempImg3Str?:@"" forKey:@"img3"];

    }else{
        subUrl = @"api/cgjl/update.ajax";
        [params setValue:kTokenID forKey:@"token"];
        [params setValue:self.modelId forKey:@"id"];
        [params setValue:self.model.img1?:@"" forKey:@"img1"];
        [params setValue:self.model.img2?:@"" forKey:@"img2"];
        
    }
    [HUDManager showLoadingHUDView:self.view];
    [NetWork PostNetWorkWithUrl:subUrl with:params successBlock:^(NSDictionary *dic) {
        [HUDManager showWarningWithText:@"修改成功"];
        [self.navigationController popViewControllerAnimated:YES];
        
    } FailureBlock:^(NSString *msg) {
        [HUDManager showWarningWithText:msg];
        BOOL ishow = self.array.count ? NO : YES;
        [self.collectionview showNoView:nil image:nil certer:CGPointZero isShow:ishow];
        
        
    } errorBlock:^(id error) {
        BOOL ishow = self.array.count ? NO : YES;
        [self.collectionview showNoView:nil image:nil certer:CGPointZero isShow:ishow];
        
        
    }];
}
@end
